package org.user.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.common.util.JwtUtils;
import org.common.util.RedisCommon;
import org.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.user.domain.pojo.UserLogin;
import org.user.domain.pojo.UserRegister;
import org.user.mapper.UserMapper;
import org.user.service.UserService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.user.util.StaticVariable.User_Jwt;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCommon redisCommon;

    @Override
    public void register(UserRegister userRegister) {
        userMapper.userRegister(userRegister);
    }

    @Override
    public UserLogin getUserLoginByPhone(String phone) {
        return userMapper.getUserLoginByPhone(phone);
    }

    @Override
    public Result login(UserLogin userLogin) throws JsonProcessingException {
        UserLogin user=userMapper.getUserLoginByPhone(userLogin.getPhone());
        if(user==null){
            return Result.error("用户不存在");
        }
        if(user.getPassword().equals(userLogin.getPassword())){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",userLogin.getId());
            claims.put("phone", userLogin.getPhone());
            String jwt= JwtUtils.getUserJwt(claims);
            redisCommon.setTemporaryCode(User_Jwt+user.getPhone(),jwt,30, TimeUnit.MINUTES);
            return new Result(200,"登录成功",jwt);
        }else {
            return Result.error("密码错误");
        }
    }
}
